package com.coisshi.base.framework.handler;


import com.coisshi.base.common.model.enums.BaseEnum;
import org.springframework.core.convert.ConversionException;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * 字符串/数字 -> 枚举类型自动转换器
 */
@Component
public class EnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) throws ConversionException {
        return new EnumConverter<>(targetType);
    }

    static class EnumConverter<T extends BaseEnum> implements Converter<String, T> {
        private final Class<T> enumType;

        public EnumConverter(Class<T> enumType) {
            this.enumType = enumType;
        }

        @Override
        public T convert(String source) throws ConversionException{
            for (T constant : enumType.getEnumConstants()) {
                if (String.valueOf(constant.getCode()).equals(source)) {
                    return constant;
                }
            }
            throw new IllegalArgumentException("无效的枚举值: " + source);
        }
    }
}
